package com.quanxiaoha.weblog.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quanxiaoha.weblog.common.domain.entity.ScheduleHabit;
import com.quanxiaoha.weblog.common.domain.mapper.ScheduleHabitMapper;
import com.quanxiaoha.weblog.common.domain.query.HabitCountQuery;
import com.quanxiaoha.weblog.common.domain.query.HabitQuery;
import com.quanxiaoha.weblog.common.entity.ScheduleHabitContent;
import com.quanxiaoha.weblog.common.entity.ScheduleHabitItem;
import com.quanxiaoha.weblog.common.service.IScheduleHabitContentService;
import com.quanxiaoha.weblog.common.service.IScheduleHabitItemService;
import com.quanxiaoha.weblog.common.service.IScheduleHabitService;
import com.quanxiaoha.weblog.common.service.IScheduleRewardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Roy
 * @since 2025-05-28
 */
@Service
public class ScheduleHabitServiceImpl extends ServiceImpl<ScheduleHabitMapper, ScheduleHabit> implements IScheduleHabitService {

    @Autowired
    @Lazy
    private IScheduleRewardService  scheduleRewardService;

    @Autowired
    private IScheduleHabitItemService scheduleHabitItemService;

    @Autowired
    private IScheduleHabitContentService scheduleHabitContentService;

    @Resource
    ThreadPoolTaskExecutor taskExecutor;


    @Override
    public Page<ScheduleHabit> getHabitList(HabitQuery habitQuery) {
        LambdaQueryWrapper<ScheduleHabit> queryWrapper = new LambdaQueryWrapper<>();
        // 根据名称模糊查询
        if (habitQuery.getHabitName() != null) {
            queryWrapper.like(ScheduleHabit::getHabitName, habitQuery.getHabitName());
        }
        // 根据难度查询
        if (habitQuery.getDifficulty() != null) {
            queryWrapper.eq(ScheduleHabit::getDifficulty, habitQuery.getDifficulty());
        }
        // 根据等级查询
        if (habitQuery.getHabitLevel() != null) {
            queryWrapper.eq(ScheduleHabit::getHabitLevel, habitQuery.getHabitLevel());
        }
        
        return this.page(new Page<>(habitQuery.getPageNum(), habitQuery.getPageSize()), queryWrapper);
    }

    @Override
    public ScheduleHabit getHabitDetail(Integer id) {
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createHabit(ScheduleHabit habit) {
        habit.setCreateTime(LocalDateTime.now());
        habit.setUpdateTime(LocalDateTime.now());
        this.save(habit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHabit(ScheduleHabit habit) {
        habit.setUpdateTime(LocalDateTime.now());
        this.updateById(habit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHabit(Integer id) {
        this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateCompletedCount(HabitCountQuery query) {

        Integer reward = 0;
        ScheduleHabit habit = this.getById(query.getId());
        if (habit != null) {
            habit.setCompletedCount(query.getCompletedCount());
            habit.setUpdateTime(LocalDateTime.now());
            this.updateById(habit);
            //更新习惯
            updateHabitItem(habit.getHabitName());


            try {
                //更新内容
                if(query.getIsContent() == 2){
                    ScheduleHabitContent scheduleHabitContent = new ScheduleHabitContent();
                    scheduleHabitContent.setHabitId(habit.getId());
                    scheduleHabitContent.setHabitContent(query.getHabitContent());
                    scheduleHabitContentService.save(scheduleHabitContent);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

            try {
                reward = scheduleRewardService.saveHabitReward();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        switch (reward){
            case 0:
                return "很遗憾没有获得积分";
            case 1:
                return "恭喜你获得了"+reward+"积分";
            case 2:
                return "恭喜你获得了"+reward+"积分";
            case 7:
                return "恭喜你获得了游龙积分";
            case 9:
                return "恭喜你获得了至尊积分";
            case 10:
                return "恭喜你获得了球王积分";
            default:
                return "很遗憾没有获得积分";
        }
    }

    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    void updateHabitItem(String habitName) {

        try {
            // 获取当天的 00:00:00 和 23:59:59.999
            LocalDateTime start = LocalDate.now().atStartOfDay(); // 当天开始时间
            LocalDateTime end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX); // 当天结束时间

            // 使用 LambdaQueryWrapper（避免硬编码字段名）
            LambdaQueryWrapper<ScheduleHabitItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.between(ScheduleHabitItem::getCreateTime, start, end); // 字段名通过方法引用指定
            wrapper.eq(ScheduleHabitItem::getHabitName, habitName);
            wrapper.last("limit 1");

            ScheduleHabitItem byId = scheduleHabitItemService.getOne(wrapper);
            if (byId != null) {
                byId.setUpdateTime(LocalDateTime.now());
                byId.setCompletedCount(byId.getCompletedCount() + 1);
                scheduleHabitItemService.updateById(byId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void initToday() {

        try {
            LocalDateTime now = LocalDateTime.now();
            //检索所有的数据
            List<ScheduleHabit> list = this.list();
            List<ScheduleHabitItem> items = list.stream().map(x -> {
                ScheduleHabitItem scheduleHabitItem = new ScheduleHabitItem();
                scheduleHabitItem.setCompletedCount(0);
                scheduleHabitItem.setHabitName(x.getHabitName());
                scheduleHabitItem.setHabitLevel(x.getHabitLevel());
                scheduleHabitItem.setCreateTime(now);
                return scheduleHabitItem;
            }).collect(Collectors.toList());
            scheduleHabitItemService.saveBatch(items);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
